package oj.hot100;

public class 零钱兑换 {
    //动态规划完全背包问题
    //优化前
    public int coinChangePre(int[] coins, int amount) {
        int n = coins.length,m = amount;
        int[][] dp = new int[n+1][m+1];
        int max = 0x3f3f3f3f;
        for(int j = 1;j <= m;j++) {
            dp[0][j] = max;
        }
        for(int i = 1;i <= n;i++) {
            for(int j = 0;j <= m;j++) {
                dp[i][j] = dp[i-1][j];
                if(j >= coins[i-1]) {
                    dp[i][j] = Math.min(dp[i][j],dp[i][j-coins[i-1]]+1);
                }
            }
        }
        return dp[n][m] == max ? -1 : dp[n][m];
    }
    //优化后
    //删除第一维,第二维从左往右遍历
    public int coinChange(int[] coins, int amount) {
        int n = coins.length,m = amount;
        int[] dp = new int[m+1];
        int max = 0x3f3f3f3f;
        for(int j = 1;j <= m;j++) {
            dp[j] = max;
        }
        for(int i = 1;i <= n;i++) {
            for(int j = coins[i-1];j <= m;j++) {
                dp[j] = Math.min(dp[j],dp[j-coins[i-1]]+1);
            }
        }
        return dp[m] == max ? -1 : dp[m];
    }
}
